import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { BusinessCircleService } from '../business-circle.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { defalutImg } from '../comm';
import { PermissionService } from '../../../service/permission.service';

@Component({
  selector: 'app-post-type',
  templateUrl: './post-type.component.html',
  styleUrls: ['./post-type.component.scss']
})
export class PostTypeComponent implements OnInit {

  // seachForm
  seachParams: any = {
    boardId: '' // 板块
  }
  // 板块下拉
  plateOptions: any = [];
  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0,
    pages: 0
  };
  // 表格data
  tableData: any = [];

  /******************** model START *********************/
  isModelVisible: boolean = false;
  modelType: number = 0; // 0：新增，1：编辑
  updateItem: any = {};
  subLoading: boolean = false;
  validateForm!: FormGroup;
  /******************** model END *********************/

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private router: Router,
    private services: BusinessCircleService,
    public permission: PermissionService,
  ) { }

  ngOnInit(): void {
    this.queryPlateList();
    this.validateForm = this.fb.group({
      typeName: ['', [Validators.required]], // 分类名称
      boardId: ['', [Validators.required]], // 所属板块
      sort: ['', [Validators.required]], // 排序
      status: ['', [Validators.required]] // 状态
    });

    this.loadTable();
  }

  // 查询板块下拉
  async queryPlateList() {
    try {
      const res: any = await this.services.getCircleTableData();
      if (res.code == 0) {
        this.plateOptions = res.data || [];
      }
    } catch (error) {
      this.plateOptions = [];
      // console.log(error);
    }
  }

  // 查询table
  async loadTable() {
    try {
      this.tableForms.tableLoading = true;
      const res: any = await this.services.getPostsTypeTableData({...this.seachParams});
      this.tableForms.tableLoading = false;
      if (res.code == 0) {
        this.tableData = res.data || [];
      }
    } catch (error) {
      this.tableForms.tableLoading = false;
      this.tableData = [];
      // console.log(error);
    }
  }

  queryData() {
    this.tableForms.page = 1;
    this.loadTable();
  }
  resetData() {
    this.seachParams.boardId = '';
    this.tableForms.page = 1;
    this.loadTable();
  }

  /**
   * open model
   * @param num 0：新增，1：编辑
   */
  openModel(num: number, item?: any) {
    this.validateForm.reset();
    this.modelType = num;
    this.updateItem = item;

    if (num == 1) {
      for (let key in this.validateForm.value) {
        if (key == 'boardId') {
          this.validateForm.get(key)?.setValue(item[key]);
        } else {
          this.validateForm.get(key)?.setValue(String(item[key]));
        }
      }
    }
    this.isModelVisible = true;
  }

  // 新增 || 编辑 submit
  async handleOk() {
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
    if (!this.validateForm.valid) {
      return
    }

    try {
      let res: any;
      this.subLoading = true;
      if (this.modelType == 0) {
        res = await this.services.addPostsTypeItemData({...this.validateForm.value});
      } else {
        res = await this.services.updatePostsTypeItemData({...this.validateForm.value, id: this.updateItem.id});
      }
      this.subLoading = false;

      if (res.code == 0) {
        this.message.success('操作成功');
        this.loadTable();
        this.isModelVisible = false;
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error) {
      // console.log(error);
      this.subLoading = false;
    }
  }

  handleCancel(): void {
    this.isModelVisible = false;
  }

  // 删除
  async deleteItem(item: any) {
    try {
      const res: any = await this.services.updatePostsTypeItemData({id: item.id, deleteState: 1});
      if (res.code == 0) {
        this.message.success('删除成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error) {
      // console.log(error);
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable();
  }

  // 板块文字转化
  transformText(boardId: any) {
    let aIndex = this.plateOptions.findIndex((item: any) => { return boardId == item.id });
    if (aIndex == -1) {
      return '-';
    } else {
      return this.plateOptions[aIndex].boardName;
    }
  }
}
